package core;

import javax.microedition.rms.*;

public class RMSManager
{
	private String nameRMS;
	
	public RMSManager(String name)
	{
		nameRMS = name;
	}
	
	public String load(String key)//�������� ������ �� RecordStore
	{
		String str = "";
		try
		{
			RecordStore recordStore = RecordStore.openRecordStore(nameRMS, true);
			RecordEnumeration re = recordStore.enumerateRecords(null, null, false);
			if (re.numRecords()!=0)
			{
				re.rebuild();
				while (re.hasNextElement())
				{
					int id = re.nextRecordId();
					String s;
					try
					{
						s = new String(recordStore.getRecord(id));
					}
					catch(Exception e){s="";};
					if (s.indexOf(key)==0)
					{
						str = s.substring(key.length()+1);
						break;
					}
				}
			}
			recordStore.closeRecordStore();
			re.destroy();
		}catch(RecordStoreException rse){};
		return Decoder.fromUnicodeRMS(str);
	}
	
	//���������� ������ � RecordStore.������ -  save("rempass=yes","rempass");
	public void save(String val,String key)
	{
		try
		{
			RecordStore recordStore = RecordStore.openRecordStore(nameRMS, true);
			RecordEnumeration re = recordStore.enumerateRecords(null, null, false);
			re.rebuild();
			byte[] res = new byte[val.length()];
			for (int i=0;i<val.length();i++)
			{
				int num = (int)val.charAt(i);
				if (num>=1040&&num<=1103)
				{
					num -= 848;
				}
				res[i] = (byte)num;
			}
			while (re.hasNextElement())
			{
				int id = re.nextRecordId();
				String s;
				try
				{
					s = new String(recordStore.getRecord(id));
				}
				catch(Exception e){s="";};
				if (s.indexOf(key)==0)
				{
					recordStore.setRecord(id,res,0,res.length);
					recordStore.closeRecordStore();
					re.destroy();
					return;
				}
			}
			recordStore.addRecord(res,0,res.length);
			recordStore.closeRecordStore();
			re.destroy();
		}catch(Exception rse){};
	}

}
